package com.example.httpdemo;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class JsonUtil {
    private static Gson gson=new Gson();
    public  static CityModel[] parseCityListByGson(String jsonStr){
        List<CityModel> list=new ArrayList<>();
        Type type=new TypeToken<WeatherObj<CityModel>>(){}.getType();
        WeatherObj<CityModel> result=gson.fromJson(jsonStr,type);
        return  result.getResult();
        }



    public static List<CityModel> parseCityList(String jsonStr) throws JSONException {
        List<CityModel> list=new ArrayList<>();
        //json标准解析遵循原则为，由内而外，层层解析
        JSONObject resultObject=new JSONObject(jsonStr);
        //判断字段是否存在
        if (resultObject.has("result")){
            //获取json数组
            JSONArray result=resultObject.getJSONArray("result");
            for (int i = 0; i < result.length(); i++) {
                JSONObject city=result.getJSONObject(i);
                CityModel cityModel=new CityModel();
                if (city.has("id")){
                    cityModel.setId(city.getString("id"));
                }
                if (city.has("province")){
                    cityModel.setProvince(city.getString("province"));
                }
                if (city.has("city")){
                    cityModel.setCity(city.getString("city"));
                }
                if (city.has("district")){
                    cityModel.setDistrict(city.getString("district"));
                }
                list.add(cityModel);
            }

        }
        return list;
    }
}
